import request from '@/api/request'
import { AxiosPromise } from 'axios'
import {base64Client} from '@/utils/common'

enum API {
    LOGIN_URL = "/auth/oauth2/token",
    CONSENT_INFO_URI = "/auth/oauth2/consent",
    CONSENT_SUBMIT_URI = "/auth/oauth2/authorize",
    SEND_CODE_URI = "/auth/oauth2/token",
    LOGOUT_URI = "/auth/logout",
    PHONECODE_URI = "/auth/phone_code"
}

export const loginApi = (data: any): AxiosPromise<any> => {
    return request.post<any>(API.LOGIN_URL,{
        grant_type: 'password',
        scope: import.meta.env.VITE_OAUTH2_SCOPES,
        ...data
    }, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': base64Client()
        }
    }
    )
}

export const logoutApi = (): AxiosPromise<any> => {
    return request.post<any>(API.LOGOUT_URI)
}

export const consentInfoApi = (params: any): AxiosPromise<any> => {
    return request.get<any>(API.CONSENT_INFO_URI, { params })
}

export const consentSubmitApi = (data: any): AxiosPromise<any> => {
    return request.post<any>(API.CONSENT_SUBMIT_URI, data)
}

export const sendCodeApi = (code: string): AxiosPromise<any> => {
    const clientCredentials = base64Client()
    const redirectURI = import.meta.env.VITE_OAUTH2_REDIRECT_URI
    const formData = new FormData()
    formData.append('grant_type', 'authorization_code')
    formData.append('redirect_uri', redirectURI)
    formData.append('code', code)
    return request.post<any>(API.SEND_CODE_URI, formData, {
        headers: {
            'Authorization': clientCredentials
        },
    })
}

export const refreshTokenApi = (): AxiosPromise<any> => {
    const clientCredentials = base64Client()
    const refreshToken = localStorage.getItem('refresh_token') as string
    return request.post<any>(API.SEND_CODE_URI,{
        grant_type: 'refresh_token',
        refresh_token: refreshToken
    },{
        headers:{
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization':clientCredentials
        }
    })
}

export const getPhoneCode = (phone:string): AxiosPromise<any> => {
    return request.get<any>(API.SEND_CODE_URI,{
        params:{
            phone
        }
    })
}